import runSaga from "./runSaga";
import createChannel from './channel';
import { take } from "./effects";

function createSagaMiddleware() {
    let channel = createChannel(); // {take, put}
    let boundRunSaga;
    // 返回一个中间件
    function sagaMiddleWare({ getState, dispatch }) {
        boundRunSaga = runSaga.bind(null, { getState, dispatch, channel });
        return function(next) {
            // 重写dispatch方法
            return function(action) {
                // 触发dispatch(action)，非异步action，直接这里触发
                let result = next(action);
                // 发布take保存的函数
                channel.put(action);
                return result;
            }
        }
    }
    // 中间件上的run方法，用于启动saga
    sagaMiddleWare.run = (saga) => boundRunSaga(saga);

    return sagaMiddleWare;
}

export default createSagaMiddleware;
